// 编写 store
// 商品列表：分类+商品
// 购物车状态： 添加 + 高亮显示

import {createSlice} from "@reduxjs/toolkit"
import axios from "axios";

const foodListStore = createSlice({
    name: "foods",
    initialState: {
        // 商品列表
        foodList: [],
        // 菜单列表激活下标值
        activeIndex: 0,
        // 购物车列表
        cartList: [],
    },
    reducers: {
        // 更改商品列表
        setFoodList(state, action) {
            state.foodList = action.payload
        },
        // 更改 activeIndex
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        // 添加购物车
        addCart(state, action) {
            // 是否添加过
            // 以 action.payload.id 去 cartList 中匹配
            // item 表示找到的那一项
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                // 已经添加过
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        // 购物车商品 count +
        increCount(state, action) {
            // 应该修改谁的 count
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        // 购物车商品 count -
        decreCount(state, action) {
            // 应该修改谁的 count
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item.count === 0) {
                return
            }
            item.count--
        },
        // 清除购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})

// 异步获取部分
const {setFoodList, changeActiveIndex, addCart, increCount, decreCount, clearCart} = foodListStore.actions
const fetchFoodList = () => {
    return async (dispatch) => {
        // 编写异步逻辑
        const res = await axios.get("http://localhost:3004/takeaway")
        // 调用 dispatch 函数提交 action
        dispatch(setFoodList(res.data))
    }
}

export {fetchFoodList, changeActiveIndex, addCart, increCount, decreCount, clearCart}

const foodListReducer = foodListStore.reducer
export default foodListReducer